package cn.demarcia.coco;

import android.support.v4.app.ActivityCompat;

import java.lang.ref.WeakReference;

import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.PermissionUtils;

public final class PermissionsDispatcher {
    private static final int REQUEST_ALL = 5;
    private static final String[] PERMISSIONS_ALL = new String[]{
            "android.permission.CAMERA",
            "android.permission.ACCESS_FINE_LOCATION",
            "android.permission.READ_PHONE_STATE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};

    private PermissionsDispatcher() {
    }

    static void checkPermissions(AppStart target) {
        if (PermissionUtils.shouldShowRequestPermissionRationale(target, PERMISSIONS_ALL)) {//再次请求权限时需要说明原因
            target.showRationaleForPermission(new AllPermissionsRequest(target));
        } else {
            ActivityCompat.requestPermissions(target, PERMISSIONS_ALL, REQUEST_ALL);
        }
    }

    static void onRequestPermissionsResult(AppStart target, int requestCode, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_ALL:
                if (PermissionUtils.getTargetSdkVersion(target) < 23 && !PermissionUtils.hasSelfPermissions(target, PERMISSIONS_ALL)) {
                    target.onPermissionDenied();
                    return;
                }
                if (!PermissionUtils.verifyPermissions(grantResults)) {
                    if (!PermissionUtils.shouldShowRequestPermissionRationale(target, PERMISSIONS_ALL)) {
                        target.onPermissionNeverAskAgain();
                    } else {
                        target.onPermissionDenied();
                    }
                    return;
                }
                target.onGetPermissions();
                break;
            default:
                break;
        }
    }

    private static final class AllPermissionsRequest implements PermissionRequest {
        private final WeakReference<AppStart> weakTarget;

        private AllPermissionsRequest(AppStart target) {
            this.weakTarget = new WeakReference<>(target);
        }

        @Override
        public void proceed() {
            AppStart target = weakTarget.get();
            if (target == null) return;
            ActivityCompat.requestPermissions(target, PERMISSIONS_ALL, REQUEST_ALL);
        }

        @Override
        public void cancel() {
        }
    }
}